<?php
/**
 * PHP的简单缓存(只能保存变量,避免序列化)
 *
 * @filesource datafile.class.php
 * @package peck
 * @subpackage _cache
 * @version $id: 1.2, utf8, Sun Dec 13 21:21:01 CST 2009
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2009 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example 
 *  require_once 'DsCache.interface.php';
 *  require_once 'datafile.class.php';
 *  $cache = new datafile( array('cache_dir'=>'/tmp', ... ) );
 *  ... 
 */
class datafile implements _dscache{

	/**
     * 写入缓存
     *
     * @param string $id
     * @param mixed $data
     * @param int $expiration
     */
    public function set($id, $data, $expiration = null){
    	$life_time = is_null($expiration) ? $this->_default_policy['life_time'] : $expiration;
        $path = $this->_path($id);
        
        if ($life_time != 0) {
        	$life_time += time();
        }
        $content = array(
            'expired' => $life_time,
            'data'    => $data,
        );
        $content = '<?php return ' . var_export($content, true) . ';';

        file_put_contents($path, $content, LOCK_EX);
        file_put_contents($path, php_strip_whitespace($path), LOCK_EX);
        clearstatcache();
        return true;
    }
	
    /**
     * 读取缓存，失败或缓存撒失效时返回 false
     *   缓存时间为0, 不检查缓存时间
     *
     * @param string $id
     * @param int $expiration
     *
     * @return mixed
     */
    public function get($id, $expiration = null){
        $path = $this->_path($id);
        
        if (!is_file($path)) return false; 

        $data = include($path);
        if (!is_array($data) || !isset($data['expired'])) return false;

        if ($data['expired'] == 0 OR $expiration == 0){
            return $data['data'];
        }else{
            return ($data['expired'] > time()) ? $data['data'] : false;
        }
    }

}//END class datafile
?>
